package com.houdoudou.affair.app;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.houdoudou.bean.AppBack;
import com.houdoudou.bean.Box;
import com.houdoudou.bean.Courier;
import com.houdoudou.bean.Distribute;
import com.houdoudou.bean.Machine;
import com.houdoudou.bean.Order;
import com.houdoudou.bean.PasswordUtil;
import com.houdoudou.bean.Supplier;
import com.houdoudou.bean.TransPasswordUtil;
import com.houdoudou.common.DateTimeFunction;
import com.houdoudou.dao.BoxDao;
import com.houdoudou.dao.BoxUsageDao;
import com.houdoudou.dao.ConnFactory;
import com.houdoudou.dao.CourierDao;
import com.houdoudou.dao.DistributeDao;
import com.houdoudou.dao.MachineDao;
import com.houdoudou.dao.OrderDao;
import com.houdoudou.dao.SupplierDao;

public class MachineAffairApp1 {

	
	
/*------------------------------------------消费者登陆-------------------------------------------------*/	
	
	public static void login(HttpServletRequest req, HttpServletResponse resp) throws IOException{		

	
		Machine machine = null;
		JSONObject backJO= new JSONObject();
		//获取Bean---------------------------
		try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println(jsonData);
		 JSONObject dataJO= JSONObject.fromObject(jsonData);
		 JSONObject machineJO= dataJO.getJSONObject("machine");	 
		 machine= (Machine) JSONObject.toBean(machineJO, Machine.class);		
	
		 }catch(Exception e2){
			 e2.printStackTrace();	
			 new AppBack(req,resp ).send(1,"传入参数不对");
			    return ;
		 }
	
		//调用 dao处理事务 -------------------------
		Connection conn = null;
		try{
		   conn= ConnFactory.getConn();
		  
		   MachineDao machineDao= new  MachineDao(conn);	  
			Machine machineExist=  machineDao.selectById(machine.getId());
			if(machineExist==null){
				new AppBack(req,resp).send(1, "自提柜不存在");
				 return;
				
			}else{
				 machineExist= Machine.decrypt(machineExist);
				 machineExist= Machine.transEncrypt(machineExist);
				if(machineExist.getSecret().equals(machine.getSecret())){
	
					backJO.put("machine", JSONObject.fromObject(machineExist));
					new AppBack(req,resp,backJO).send(2, "登陆成功");
					 return;
				}else{
					new AppBack(req,resp).send(1, "密码错误");
					 return;
				}		  
			}
		}catch(Exception e){
			e.printStackTrace();
			new AppBack(req,resp).send(1, "数据库异常");
			 return;
			
		}finally{
			 ConnFactory.closeConn(conn);	
				
		}
				 
	}
	/*------------------------------------------拉取新订单------------------------------------------------*/	
public static void frequentlyPull(HttpServletRequest req, HttpServletResponse resp) throws IOException{		
		
		Machine machine = null;
		JSONObject backJO= new JSONObject();
		//获取Bean---------------------------
		try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println(jsonData);
		 JSONObject dataJO= JSONObject.fromObject(jsonData);
		 JSONObject machineJO= dataJO.getJSONObject("machine");	 
		 machine= (Machine) JSONObject.toBean(machineJO, Machine.class);		
	
		 }catch(Exception e2){
			 e2.printStackTrace();	
			 new AppBack(req,resp ).send(1,"传入参数不对");
			    return ;
		 }
	
		//调用 dao处理事务 -------------------------
		Connection conn = null;
		try{
		   conn= ConnFactory.getConn();
		   
		   if(! isMachineValid(conn, machine)){
		      	new AppBack(req,resp).send(1, "自提柜验证失败");
		        return ;
		         }	
		   
		   Order searchOrder= new Order();
		   searchOrder.setMachineID(machine.getId());
		   searchOrder.setState(11); //搜索商家已经确认的订单。
		   List<Order> orders= new OrderDao(conn).search(OrderDao.getSearchSql(searchOrder));	   
		   backJO.put("orders", JSONArray.fromObject(orders));
			new AppBack(req,resp,backJO).send(2, "搜索成功");
		}catch(Exception e){
			e.printStackTrace();
			new AppBack(req,resp).send(1, "数据库异常");
			 return;
			
		}finally{
			 ConnFactory.closeConn(conn);	
				
		}
				 
	}
	
public static void changeOrderState(HttpServletRequest req, HttpServletResponse resp) throws IOException{		
		
		Machine machine = null;
		 List<Order> orders;
		JSONObject backJO= new JSONObject();
		
		int oldState=-1,newState=-1;
		//获取Bean---------------------------
		try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println(jsonData);
		 JSONObject dataJO= JSONObject.fromObject(jsonData);
		 JSONObject machineJO= dataJO.getJSONObject("machine");	 
		 machine= (Machine) JSONObject.toBean(machineJO, Machine.class);
		 JSONArray orderJA= dataJO.getJSONArray("orders");
		 orders= JSONArray.toList(orderJA, Order.class);
		 oldState= dataJO.getInt("oldState");
		 newState=dataJO.getInt("newState");
	
		 }catch(Exception e2){
			 e2.printStackTrace();	
			 new AppBack(req,resp ).send(1,"传入参数不对");
			    return ;
		 }
	
		//调用 dao处理事务 -------------------------
		Connection conn = null;
		try{
		   conn= ConnFactory.getConn();
		   
		   if(! isMachineValid(conn, machine)){
		      	new AppBack(req,resp).send(1, "自提柜验证失败");
		        return ;
		         }	
		   conn.setAutoCommit(false);
		  OrderDao orderDao= new OrderDao(conn);
		   for(int i= orders.size()-1;i>=0;i--){
			   Order orderExist = orderDao.selectById(orders.get(i).getId());
			   if(orderExist.getState()==oldState){
				   String sql= "update tb_order set state="+ newState+" where id=" +orders.get(i).getId();  
				   System.out.println(sql);
				   orderDao.update(sql);
			   }else{
				   orders.remove(i);
			   }		  
		   }    
		   conn.commit();
		   backJO.put("orders", JSONArray.fromObject(orders));
			new AppBack(req,resp,backJO).send(2, "更新成功");
		}catch(Exception e){
			try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
			e.printStackTrace();
			new AppBack(req,resp).send(1, "数据库异常");
			 return;
			
		}finally{
			 ConnFactory.closeConn(conn);	
				
		}
				 
	}

/*------------------------------------------送货员登陆-------------------------------------------------*/	

public static void courierLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException{		
	
	Machine machine = null;
	Courier courier=null;
	JSONObject backJO= new JSONObject();
	//获取Bean---------------------------
	try{
	 String jsonData= req.getParameter("jsonData");
	 System.out.println(jsonData);
	 JSONObject dataJO= JSONObject.fromObject(jsonData);
	 JSONObject machineJO= dataJO.getJSONObject("machine");	 
	 machine= (Machine) JSONObject.toBean(machineJO, Machine.class);		
     JSONObject courierJO= dataJO.getJSONObject("courier");
     courier= (Courier) JSONObject.toBean(courierJO, Courier.class);
	 
	 }catch(Exception e2){
		 e2.printStackTrace();	
		 new AppBack(req,resp ).send(1,"传入参数不对");
		    return ;
	 }

	//调用 dao处理事务 -------------------------
	Connection conn = null;
	try{
	   conn= ConnFactory.getConn();
	  
	   CourierDao  courierDao= new  CourierDao(conn);	  
		Courier courierExist= courierDao.selectById(courier.getTelnum());
		if(courierExist==null){
			new AppBack(req,resp).send(1, "该送货员不存在");
			 return;
			
		}
		
			String secret= PasswordUtil.decrypt(courierExist.getSecret());
			secret= TransPasswordUtil.encrypt(secret);
			if(!secret.equals(courier.getSecret())){
				new AppBack(req,resp).send(1, "密码错误");
				 return;
			}
			      int current_TimeFlag= figureoutTimeFlag(machine);
			      if(current_TimeFlag==-1){
			    	  String noteStr="本时间点不能登录，快递员登录时间段为：";
			    	  noteStr+=machine.getTimeAEM().substring(0,2)+":"+machine.getTimeAEM().substring(2,4)+"~"+machine.getTimeRLM().substring(0,2)+":"+machine.getTimeRLM().substring(2,4);
			    	  noteStr+="   "+machine.getTimeAEN().substring(0,2)+":"+machine.getTimeAEN().substring(2,4)+"~"+machine.getTimeRLN().substring(0,2)+":"+machine.getTimeRLN().substring(2,4);	
			    	  noteStr+="   "+machine.getTimeAEE().substring(0,2)+":"+machine.getTimeAEE().substring(2,4)+"~"+machine.getTimeRLE().substring(0,2)+":"+machine.getTimeRLE().substring(2,4);	
			    	  new AppBack(req,resp).send(1, noteStr);  return;
			      }
				 if(courierExist.getType()==1){
					 backJO.put("courier", JSONObject.fromObject(courierExist));
					  backJO.put("timeFlag", current_TimeFlag);
                	 new AppBack(req,resp,backJO).send(2, "登陆成功"); return;
				 }
                 if(courierExist.getType()==2){
                	 if(courierExist.getBelong().equals(machine.getOwner())){ 
                		 backJO.put("courier", JSONObject.fromObject(courierExist));
                		  backJO.put("timeFlag", current_TimeFlag);
                	 new AppBack(req,resp,backJO).send(2, "登陆成功"); return;}
                 }
                 if(courierExist.getType()==3){
                	 Distribute distribute = new Distribute();
                	 distribute.setSupplier(courierExist.getBelong());
                	 distribute.setMachine(machine.getId());
                List<Distribute> distributes=new DistributeDao(conn).search(DistributeDao.getSearchSql(distribute));
                      if(distributes.size()==0){                  	
                        	  new AppBack(req,resp).send(1, "你无权登陆该自提柜"); 
                        	  return;                        
                      }
                      String hourSencondNow=  DateTimeFunction.myDateFormat(new Date()).substring(8, 12);
                      long nowSeconds= DateTimeFunction.myDateTimeValue(hourSencondNow);
                      long timeEvalue=-1;
                      long timeLvalue=-1;
                      String timeE = ""; String timeL="";
                      String time_Peroid="";
                    	  for(int i=0;i<distributes.size();i++){
                    		 
                    		  if(distributes.get(i).getTimeFlag()==1){
               				          timeEvalue=DateTimeFunction.myDateTimeValue(machine.getTimeAEM());
                    				  timeLvalue=DateTimeFunction.myDateTimeValue(machine.getTimeRLM());
                    				  
                    				  if(nowSeconds>=timeEvalue&&nowSeconds<=timeLvalue){
                        				  backJO.put("courier", JSONObject.fromObject(courierExist));
                        				  backJO.put("timeFlag", current_TimeFlag);
                                      	 new AppBack(req,resp,backJO).send(2, "登陆成功");  return;
                        			  }
                    				  
                    				 timeE= machine.getTimeAEM().substring(0,2)+":"+machine.getTimeAEM().substring(2,4);
                    				 timeL= machine.getTimeRLM().substring(0,2)+":"+machine.getTimeRLM().substring(2,4);                 				
                    		         time_Peroid+=timeE+"-"+timeL;
                    		  }
                    		  
                    		  if(distributes.get(i).getTimeFlag()==2){                   			 	
                				  timeLvalue=DateTimeFunction.myDateTimeValue(machine.getTimeRLN());    
                				  timeEvalue=DateTimeFunction.myDateTimeValue(machine.getTimeAEN()); 
                				  
                				  if(nowSeconds>=timeEvalue&&nowSeconds<=timeLvalue){
                    				  backJO.put("courier", JSONObject.fromObject(courierExist));
                    				  backJO.put("timeFlag", current_TimeFlag);
                                  	 new AppBack(req,resp,backJO).send(2, "登陆成功");  return;
                    			  }
                				  
                				 timeE= machine.getTimeAEN().substring(0,2)+":"+machine.getTimeAEN().substring(2,4);
                				 timeL= machine.getTimeRLN().substring(0,2)+":"+machine.getTimeRLN().substring(2,4);         
                				 time_Peroid+=timeE+"-"+timeL;
                    		  }
                    		  
                    		  if(distributes.get(i).getTimeFlag()==3){
                    			  timeLvalue=DateTimeFunction.myDateTimeValue(machine.getTimeRLE());
                    			 timeEvalue=DateTimeFunction.myDateTimeValue(machine.getTimeAEE()); 		
                    			 
                    			  if(nowSeconds>=timeEvalue&&nowSeconds<=timeLvalue){
                    				  backJO.put("courier", JSONObject.fromObject(courierExist));
                    				  backJO.put("timeFlag", current_TimeFlag);
                                  	 new AppBack(req,resp,backJO).send(2, "登陆成功");  return;
                    			  }
                    			  
                				 timeE= machine.getTimeAEE().substring(0,2)+":"+machine.getTimeAEE().substring(2,4);
                				 timeL= machine.getTimeRLE().substring(0,2)+":"+machine.getTimeRLE().substring(2,4); 
                				 time_Peroid+=timeE+"-"+timeL;
                    		  } 
                    	  }
                   	
                    	  new AppBack(req,resp).send(1, "你只能在如下时间段内登陆 "+time_Peroid); 
                               
                 }
                         				  
	
	}catch(Exception e){
		e.printStackTrace();
		new AppBack(req,resp).send(1, "数据库异常");
		 return;
		
	}finally{
		 ConnFactory.closeConn(conn);	
			
	}
			 
}

private  static int  figureoutTimeFlag( Machine machine){
	int timeFlag=-1;
	 long timeEvalue=-1;
     long timeLvalue=-1;
     String hourSencondNow=  DateTimeFunction.myDateFormat(new Date()).substring(8, 12);
     long timeNow= DateTimeFunction.myDateTimeValue(hourSencondNow);
     
	 timeEvalue=DateTimeFunction.myDateTimeValue(machine.getTimeAEM());
	  timeLvalue=DateTimeFunction.myDateTimeValue(machine.getTimeRLM());
	  System.out.println("timeEvalue="+timeEvalue+"timeLvalue="+timeLvalue+"timeNow="+timeNow);
	  if(timeNow>=timeEvalue&&timeNow<=timeLvalue) return 1; //快递员处理早班任务
	  
	  timeEvalue=DateTimeFunction.myDateTimeValue(machine.getTimeAEN());
	  timeLvalue=DateTimeFunction.myDateTimeValue(machine.getTimeRLN());
	  System.out.println("timeEvalue="+timeEvalue+"timeLvalue="+timeLvalue+"timeNow="+timeNow);
	  if(timeNow>=timeEvalue&&timeNow<=timeLvalue) return 2; //快递员处理早班任务
	  
	  timeEvalue=DateTimeFunction.myDateTimeValue(machine.getTimeAEE());
	  timeLvalue=DateTimeFunction.myDateTimeValue(machine.getTimeRLE());
	  System.out.println("timeEvalue="+timeEvalue+"timeLvalue="+timeLvalue+"timeNow="+timeNow);
	  if(timeNow>=timeEvalue&&timeNow<=timeLvalue) return 3; //快递员处理早班任务
	 
	return timeFlag;
}
public static void orderArrive(HttpServletRequest req, HttpServletResponse resp) throws IOException{		
	
	Machine machine = null;
	 List<Order> orders;
	JSONObject backJO= new JSONObject();
	String courierTelnum="";
	//获取Bean---------------------------
	try{
	 String jsonData= req.getParameter("jsonData");
	 System.out.println(jsonData);
	 JSONObject dataJO= JSONObject.fromObject(jsonData);
	 JSONObject machineJO= dataJO.getJSONObject("machine");	 
	 machine= (Machine) JSONObject.toBean(machineJO, Machine.class);
	 JSONArray orderJA= dataJO.getJSONArray("orders");
	 orders= JSONArray.toList(orderJA, Order.class);
	 courierTelnum= dataJO.getString("courier");

	 }catch(Exception e2){
		 e2.printStackTrace();	
		 new AppBack(req,resp ).send(1,"传入参数不对");
		    return ;
	 }

	//调用 dao处理事务 -------------------------
	Connection conn = null;
	try{
	   conn= ConnFactory.getConn();
	   
	   if(! isMachineValid(conn, machine)){
	      	new AppBack(req,resp).send(1, "自提柜验证失败");
	        return ;
	         }	
	   conn.setAutoCommit(false);
	  OrderDao orderDao= new OrderDao(conn);
	   for(int i= orders.size()-1;i>=0;i--){
		   Order orderExist = orderDao.selectById(orders.get(i).getId());
		   if(orderExist.getState()==20||orderExist.getState()==12){
			   String sql= "update tb_order set state="+21 +", dateTimeAI="+ DateTimeFunction.myDateFormat(new Date())+", courierAITelnum="+ courierTelnum+" where id=" +orders.get(i).getId();  
			   System.out.println(sql);
			   orderDao.update(sql);
		   }else{
			   orders.remove(i);
		   }		  
	   }    
	   conn.commit();
	   backJO.put("orders", JSONArray.fromObject(orders));
		new AppBack(req,resp,backJO).send(2, "更新成功");
	}catch(Exception e){
		try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
		e.printStackTrace();
		new AppBack(req,resp).send(1, "数据库异常");
		 return;
		
	}finally{
		 ConnFactory.closeConn(conn);	
			
	}
			 
}
public static void orderTakeback(HttpServletRequest req, HttpServletResponse resp) throws IOException{		
	
	Machine machine = null;
	 List<Order> orders;
	JSONObject backJO= new JSONObject();
	String courierTelnum="";
	//获取Bean---------------------------
	try{
	 String jsonData= req.getParameter("jsonData");
	 System.out.println(jsonData);
	 JSONObject dataJO= JSONObject.fromObject(jsonData);
	 JSONObject machineJO= dataJO.getJSONObject("machine");	 
	 machine= (Machine) JSONObject.toBean(machineJO, Machine.class);
	 JSONArray orderJA= dataJO.getJSONArray("orders");
	 orders= JSONArray.toList(orderJA, Order.class);
	 courierTelnum= dataJO.getString("courier");

	 }catch(Exception e2){
		 e2.printStackTrace();	
		 new AppBack(req,resp ).send(1,"传入参数不对");
		    return ;
	 }

	//调用 dao处理事务 -------------------------
	Connection conn = null;
	try{
	   conn= ConnFactory.getConn();
	   
	   if(! isMachineValid(conn, machine)){
	      	new AppBack(req,resp).send(1, "自提柜验证失败");
	        return ;
	         }	
	   conn.setAutoCommit(false);
	  OrderDao orderDao= new OrderDao(conn);
	   for(int i= orders.size()-1;i>=0;i--){
		   Order orderExist = orderDao.selectById(orders.get(i).getId());
		   if(orderExist.getState()==21){
			   String sql= "update tb_order set state="+23 +", dateTimeRK="+ DateTimeFunction.myDateFormat(new Date())+", courierRKTelnum="+ courierTelnum+" where id=" +orders.get(i).getId();  
			   System.out.println(sql);
			   orderDao.update(sql);
			   //设置通知			   
		   }else{
			   orders.remove(i);
		   }		  
	   }    
	   conn.commit();
	   backJO.put("orders", JSONArray.fromObject(orders));
		new AppBack(req,resp,backJO).send(2, "更新成功");
	}catch(Exception e){
		try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
		e.printStackTrace();
		new AppBack(req,resp).send(1, "数据库异常");
		 return;
		
	}finally{
		 ConnFactory.closeConn(conn);	
			
	}
			 
}
public static void orderTaked(HttpServletRequest req, HttpServletResponse resp) throws IOException{		
	
	Machine machine = null;
	 List<Order> orders;
	JSONObject backJO= new JSONObject();
	String courierTelnum="";
	//获取Bean---------------------------
	try{
	 String jsonData= req.getParameter("jsonData");
	 System.out.println(jsonData);
	 JSONObject dataJO= JSONObject.fromObject(jsonData);
	 JSONObject machineJO= dataJO.getJSONObject("machine");	 
	 machine= (Machine) JSONObject.toBean(machineJO, Machine.class);
	 JSONArray orderJA= dataJO.getJSONArray("orders");
	 orders= JSONArray.toList(orderJA, Order.class);
	 }catch(Exception e2){
		 e2.printStackTrace();	
		 new AppBack(req,resp ).send(1,"传入参数不对");
		    return ;
	 }

	//调用 dao处理事务 -------------------------
	Connection conn = null;
	try{
	   conn= ConnFactory.getConn();
	   
	   if(! isMachineValid(conn, machine)){
	      	new AppBack(req,resp).send(1, "自提柜验证失败");
	        return ;
	         }	
	   conn.setAutoCommit(false);
	  OrderDao orderDao= new OrderDao(conn);
	   for(int i= orders.size()-1;i>=0;i--){
		   Order orderExist = orderDao.selectById(orders.get(i).getId());
		   if(orderExist.getState()==21){
			   String sql= "update tb_order set state="+22 +", dateTimeTK="+ DateTimeFunction.myDateFormat(new Date())+" where id=" +orders.get(i).getId();  
			   System.out.println(sql);
			   orderDao.update(sql);
			   //设置通知			   
		   }else{
			   orders.remove(i);
		   }		  
	   }    
	   conn.commit();
	   backJO.put("orders", JSONArray.fromObject(orders));
		new AppBack(req,resp,backJO).send(2, "更新成功");
	}catch(Exception e){
		try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
		e.printStackTrace();
		new AppBack(req,resp).send(1, "数据库异常");
		 return;
		
	}finally{
		 ConnFactory.closeConn(conn);	
			
	}
			 
}
public static void orderAbandom(HttpServletRequest req, HttpServletResponse resp) throws IOException{		
	
	Machine machine = null;
	 List<Order> orders;
	JSONObject backJO= new JSONObject();
	String courierTelnum="";
	//获取Bean---------------------------
	try{
	 String jsonData= req.getParameter("jsonData");
	 System.out.println(jsonData);
	 JSONObject dataJO= JSONObject.fromObject(jsonData);
	 JSONObject machineJO= dataJO.getJSONObject("machine");	 
	 machine= (Machine) JSONObject.toBean(machineJO, Machine.class);
	 JSONArray orderJA= dataJO.getJSONArray("orders");
	 orders= JSONArray.toList(orderJA, Order.class);
	 courierTelnum= dataJO.getString("courier");

	 }catch(Exception e2){
		 e2.printStackTrace();	
		 new AppBack(req,resp ).send(1,"传入参数不对");
		    return ;
	 }

	//调用 dao处理事务 -------------------------
	Connection conn = null;
	try{
	   conn= ConnFactory.getConn();
	   
	   if(! isMachineValid(conn, machine)){
	      	new AppBack(req,resp).send(1, "自提柜验证失败");
	        return ;
	         }	
	   conn.setAutoCommit(false);
	  OrderDao orderDao= new OrderDao(conn);
	   for(int i= orders.size()-1;i>=0;i--){
		   Order orderExist = orderDao.selectById(orders.get(i).getId());
		   if(orderExist.getState()==21){
			   String sql= "update tb_order set state="+24 +", dateTimeAB="+ DateTimeFunction.myDateFormat(new Date())+", courierABTelnum="+ courierTelnum+" where id=" +orders.get(i).getId();  
			   System.out.println(sql);
			   orderDao.update(sql);
			   
			   //设置通知
			   
		   }else{
			   orders.remove(i);
		   }		  
	   }    
	   conn.commit();
	   backJO.put("orders", JSONArray.fromObject(orders));
		new AppBack(req,resp,backJO).send(2, "更新成功");
	}catch(Exception e){
		try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
		e.printStackTrace();
		new AppBack(req,resp).send(1, "数据库异常");
		 return;
		
	}finally{
		 ConnFactory.closeConn(conn);	
			
	}
			 
}
public static void addBox(HttpServletRequest req, HttpServletResponse resp) throws IOException{		
	
	Machine machine = null;
	String boxesAdd=null;
    Order  order,orderExist = null;
	JSONObject backJO= new JSONObject();
	
	//获取Bean---------------------------
	try{
	 String jsonData= req.getParameter("jsonData");
	 System.out.println(jsonData);
	 JSONObject dataJO= JSONObject.fromObject(jsonData);
	 machine= (Machine) JSONObject.toBean(dataJO.getJSONObject("machine"), Machine.class);	
	 order=(Order) JSONObject.toBean(dataJO.getJSONObject("order"),Order.class);	

	 }catch(Exception e2){
		 e2.printStackTrace();	
		 new AppBack(req,resp ).send(1,"传入参数不对");
		    return ;
	 }

	//调用 dao处理事务 -------------------------
	Connection conn = null;
	try{
	   conn= ConnFactory.getConn();
	   
	   if(! isMachineValid(conn, machine)){
	      	new AppBack(req,resp).send(1, "自提柜验证失败");
	        return ;
	         }	
	   conn.setAutoCommit(false);
	  OrderDao orderDao= new OrderDao(conn);
	       
		    orderExist = orderDao.selectById(order.getId());
		    orderExist.setBoxNum(1); //一次增加1个箱格
		    BoxUsageDao boxUsageDao= new BoxUsageDao(conn);
		    boxesAdd= boxUsageDao.getIdleBox(orderExist,3); //此处的箱格应该是3表示已经支付
		    if(boxesAdd==null){ //没有空余箱格
		    	new AppBack(req,resp).send(1, "没有空余箱格"); return;
		    }else{
		    	//更新订单。
		    	order.setBoxesIn(orderExist.getBoxesIn()+boxesAdd);
		    	order.setBoxNum(order.getBoxesIn().length()/3);
		    	orderDao.update(OrderDao.getUpdateSql(order));
		    	 //新增的箱格需要更新箱格的所属订单
		    	 orderExist.setBoxesIn(boxesAdd);
		    	boxUsageDao.updateOrderId(orderExist);
		        backJO.put("boxid", boxesAdd);
		        backJO.put("orderid",order.getId());
		        new AppBack(req,resp,backJO).send(2, "增加箱格成功，箱格号码"+boxesAdd);
		        conn.commit();
		        return;
		    }		  	  
	
	}catch(Exception e){
		try {conn.rollback(); 
		if(boxesAdd!=null){ //出了错，要把新增的箱格回置空
			orderExist.setBoxesIn(boxesAdd);
		new BoxUsageDao(conn).updateBoxState(orderExist,1); conn.commit();}
		} catch (SQLException e1) {e1.printStackTrace();}
		e.printStackTrace();
		new AppBack(req,resp).send(1, "数据库异常");
		 return;
		
	}finally{
		 ConnFactory.closeConn(conn);	
			
	}
			 
}

public static void deleteOrLockBox(HttpServletRequest req, HttpServletResponse resp, boolean isLock) throws IOException{		
	
	Machine machine = null;
	String boxSubtract=null;
    Order  order,orderExist = null;
	JSONObject backJO= new JSONObject();
	
	//获取Bean---------------------------
	try{
	 String jsonData= req.getParameter("jsonData");
	 System.out.println(jsonData);
	 JSONObject dataJO= JSONObject.fromObject(jsonData);
	 machine= (Machine) JSONObject.toBean(dataJO.getJSONObject("machine"), Machine.class);	
	 order=(Order) JSONObject.toBean(dataJO.getJSONObject("order"),Order.class);	
	 boxSubtract=order.getBoxesIn();
	 }catch(Exception e2){
		 e2.printStackTrace();	
		 new AppBack(req,resp ).send(1,"传入参数不对");
		    return ;
	 }

	//调用 dao处理事务 -------------------------
	Connection conn = null;
	try{
	   conn= ConnFactory.getConn();
	   
	   if(! isMachineValid(conn, machine)){
	      	new AppBack(req,resp).send(1, "自提柜验证失败");
	        return ;
	         }	
	   conn.setAutoCommit(false);
	  OrderDao orderDao= new OrderDao(conn);
	  BoxUsageDao boxUsageDao= new BoxUsageDao(conn);
		    orderExist = orderDao.selectById(order.getId());
		    String boxesInExist= orderExist.getBoxesIn(); //保存原值
		    orderExist.setBoxesIn(boxSubtract);
		    boxUsageDao.updateBoxState(orderExist,1);	
		    
		    //更新订单		
		    String boxeInNew="";
		    for( int i=0;i<boxesInExist.length()/3;i++){
		    	String boxStr= boxesInExist.substring(i*3, (i+1)*3);
		    	if(boxStr.equals(boxSubtract)){
		    		boxeInNew= boxesInExist.substring(0,i*3)+boxesInExist.substring((i+1)*3);
		    		break;
		    	}
		    }	
		    	    
		    order.setBoxesIn(boxeInNew);
		    order.setBoxNum(boxeInNew.length()/3);
		    orderDao.update(OrderDao.getUpdateSql(order));
		        backJO.put("boxid",boxSubtract);
		        backJO.put("orderid",order.getId());
		        if(!isLock){
		        new AppBack(req,resp,backJO).send(2, "删除箱格成功，箱格号码"+boxSubtract);
		        }else{
		        	Box box= new Box();
		        	box.setMachine(orderExist.getMachineID());
		        	box.setId(Integer.parseInt(boxSubtract));
		        	box.setState(4); //故障
		        	new BoxDao(conn).update(box);
		        	new AppBack(req,resp,backJO).send(2, "锁定箱格成功，箱格号码"+boxSubtract);
		        }
		        conn.commit();
		        return;	   	  
	
	}catch(Exception e){
		try {conn.rollback(); 
		} catch (SQLException e1) {e1.printStackTrace();}
		e.printStackTrace();
		new AppBack(req,resp).send(1, "数据库异常");
		 return;
		
	}finally{
		 ConnFactory.closeConn(conn);	
			
	}
			 
}
	/*------------------------------------------验证自提柜------------------------------------------------*/	
	private static boolean isMachineValid(Connection conn,Machine machine){
		boolean result=true;
		 MachineDao machineDao= new  MachineDao(conn);	  
			Machine machineExist;
			try {
				machineExist = machineDao.selectById(machine.getId());
			if(machineExist==null){ return false;}
				 machineExist= Machine.decrypt(machineExist);
				 machineExist= Machine.transEncrypt(machineExist);
				if(machineExist.getSecret().equals(machine.getSecret())){
					 return true;
				}else{	 return false;}	
				 }
			 catch (Exception e) {
				e.printStackTrace(); return false;
			}
		
	}
}
